<template>
  <div class="history-day">
    <van-skeleton v-show="state.loading" :row="3" />
    <div v-show="!state.loading">
      <van-calendar
        :show-title="false"
        color="var(--score-primary-color)"
        :show-mark="false"
        :show-confirm="false"
        :poppable="false"
        :min-date="state.minDate"
        :max-date="state.maxDate"
        :default-date="state.defaultDate"
        :style="{ height: calendarHeight }"
        :formatter="formatter"
        @select="onSelect"
      />

      <div class="record">
        <HistoryRecord
          :list="state.recordList"
          :show-more="false"
          :week="state.todayStr"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, watch, defineProps, onBeforeUnmount } from 'vue'
import { calendarHeight } from '@/utils/globalVar'
import HistoryRecord from '@/components/HistoryRecord/Index.vue'
import { deviceId } from '@/utils/enum'
const { convertDuration, convertTime, contrastDay } = require('@/utils/util')
import { useRoute } from 'vue-router'
const route = useRoute()

const props = defineProps({})

watch(
  () => route.query,
  (to, from) => {
    if (to.random) {
      onSelect(new Date())
    } else {
      clearInterval(state.timer)
    }
  },
  {
    deep: true
  }
)

const state = reactive({
  minDate: new Date(),
  maxDate: new Date(),
  defaultDate: new Date(),
  recordList: [],
  loading: true,
  timer: undefined,
  todayStr: `${new Date().getMonth() + 1}月${new Date().getDate()}日`
})

// 获取刷牙的历史记录
const getHistoryParam = historyDay => {
  Hejia.getHistoryParam(
    {
      // deviceId,
      paramName: ['brushRecord'],
      startDate: getTimestamp(historyDay),
      endDate: getTimestamp(historyDay) + 86400000
    },
    function (arr) {
      if (arr.length) {
        /**
         * Array.prototype.filter(item, index, self)
         * description: 所有返回真值的元素值组成的新数组 =>过滤掉重复的元素
         * item 当前正在处理的元素
         * index 正在处理的元素在数组中的索引
         * self 是指数组本身
         *
         * findIndex 没有找到对应元素则返回 -1
         */
        /**
         * 过滤数据：
         * 1.过滤重复数据
         * 过滤数据的原因：因模块重复上报数据，在前端去掉该重复数据
         * 2.过滤掉不正确数据
         * 出现不正确数据的原因：数据上报时间不正确，刷牙时因为网络不好，导致该条刷牙数据未上传，等到网络好的数据，
         * 模块就会上报之前的数据，所以即使历史数据接口返回的数据会包括之前日期的数据，需要判断该刷牙数据的时间是否在
         * 当前参数（开始结束时间范围内），所以也要过滤该条数据
         */
        state.recordList = arr.filter((item, index, self) => {
          const itemVal = item.params[0].value
          return (
            index ===
            self.findIndex(obj => {
              const arrVal = obj.params[0].value
              return itemVal === arrVal
            })
          )
        })
        state.recordList = state.recordList.filter(item => {
          const { value } = item.params[0]
          const time = parseInt(value.substring(0, 8), 16)

          if (contrastDay(time, historyDay)) {
            return item
          }
        })
        // 排序
        state.recordList = state.recordList.sort((a, b) => {
          const aData = parseInt(a.params[0].value.substring(0, 8), 16)
          const bData = parseInt(b.params[0].value.substring(0, 8), 16)

          return bData - aData
        })

        // 筛选出有效刷牙时长 >=30s
        state.recordList = state.recordList.filter(item => {
          const { value } = item.params[0]
          const duration = parseInt(value.substring(10, 14), 16)
          if (duration >= 30) {
            return item
          }
        })
        state.recordList = state.recordList.map(item => {
          const { value } = item.params[0]
          const time = parseInt(value.substring(0, 8), 16)
          const score = parseInt(value.substring(8, 10), 16)
          const duration = parseInt(value.substring(10, 14), 16)
          return {
            time: convertTime(time),
            score,
            duration: convertDuration(duration),
            id: Math.random()
          }
        })
      } else {
        state.recordList = []
      }
      state.loading = false
    },
    function (msg, obj) {
      console.log(obj.resultCode + obj.resultCodeMessage)
    }
  )
}

const intervalEvent = date => {
  clearInterval(state.timer)
  state.timer = setInterval(() => {
    // getHistoryParam(new Date().getDate())
    getHistoryParam(date)
  }, 1000 * 3)
}

const d = new Date()
const currentMonth = d.getMonth()
const formatter = day => {
  if (day.type == 'disabled') {
    day.type = ''
  }
  if (day.date.getDate() == state.defaultDate.getDate()) {
    day.type = 'selected'
  }

  return day
}

function getTimestamp(day) {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth()
  const day1 = date.getDate()

  const timestamp = new Date(year, month, Number(day)).getTime()
  return timestamp
}

const onSelect = val => {
  state.defaultDate = val
  state.todayStr = `${val.getMonth() + 1}月${val.getDate()}日`
  clearInterval(state.timer)
  getHistoryParam(val.getDate())
  intervalEvent(val.getDate())
}

onMounted(() => {
  getHistoryParam(new Date().getDate())
  state.todayStr = `${new Date().getMonth() + 1}月${new Date().getDate()}日`
  clearInterval(state.timer)
  intervalEvent(new Date().getDate())
})
onBeforeUnmount(() => {
  clearInterval(state.timer)
})
</script>

<style lang="less">
.history-day {
  .record {
    margin-top: 20px;
  }
  .van-skeleton-paragraph,
  .van-skeleton-title {
    background-color: #ccc !important;
  }
}
</style>
